<template>
  <page-header-wrapper>
    <div style="background: #fff">
      <a-card>
        <div class="table-page-search-wrapper" style="border-bottom: 0px;">
          <a-form layout="inline" class="table-head-ground">
            <div class="table-layer">
              <a-form-item label="">
                <div style="border: 1px solid #ddd;">
                  <a-range-picker
                    @change="onChange"
                    :show-time="{ format: 'HH:mm:ss' }"
                    format="YYYY-MM-DD HH:mm:ss"
                    :ranges="ranges"
                    :disabled-date="disabledDate"
                    :default-value="[moment(moment().add(-6, 'days').startOf('day').valueOf()), moment(moment().endOf('day').valueOf())]"
                    @ok="queryFunc"
                    :allowClear="false"
                    style="width:400px;"
                  >
                    <div class="change-date-layout">
                      {{ jeeDate ? jeeDate : '最近七天' }}
                      <div class="pay-icon">
                        <div v-if="lastSevenDays" class="change-date-icon"><a-icon type="down" /></div>
                        <div v-else @click.stop="iconClick" class="change-date-icon" ><a-icon type="close-circle" /></div>
                      </div>
                    </div>
                  </a-range-picker>
                </div>
              </a-form-item>
            </div>
          </a-form>
        </div>

        <div class="table-page-search-wrapper">
          <div class="table-layer">
            <div style="background-color: #ececec; padding:2px">
              <a-card title="总账统计(CNY)" style="width: 100%">
                <template #extra>
                  <a-button
                    type="primary"
                    shape="round"
                    icon="download"
                    size="small"
                    @click="downLoad"
                    :loading="fileLoading">导出</a-button>
                </template>
                <div style="padding:24px;">
                  <a-row>
                    <a-col :span="4">
                      <a-statistic title="总账单" :value="totalPrice.toFixed(2) | currency" style="margin-right: 50px" />
                    </a-col>
                    <a-col :span="4" v-for="(value,key,index) in typeList" :key="index">
                      <a-statistic :title="key | dealConvert" :precision="2" :value=" value.toFixed(2) | currency " />
                    </a-col>
                  </a-row>
                </div>
              </a-card>
            </div>
            <a-table
              bordered
              :columns="tableColumns"
              row-key="appName"
              :data-source="apiResData.records.accountForMchRqs"
              :pagination="pagination"
              :loading="showLoading"
              :scroll="{ x: scrollX }"
              @change="handleTableChange"
            >
              <template slot="CurrencySlot" slot-scope="record">
                <a-tag
                  :key="record.state"
                  color="blue"
                >(人民币)CNY</a-tag>
              </template>
              <template slot="UnitSlot"><span>元</span></template>
              <template slot="bamountSlot" slot-scope="record"><b>￥{{ convertCurrency(record.totalAccountForApp.toFixed(2)) }}</b></template>
              <template slot="samountSlot" slot-scope="record">{{ record.totalAccountForApp.toFixed(2) | currency }}</template>
              <template slot="DetailSlot" slot-scope="text,record">
                <div class="order-list">
                  <div v-for="item in record.orderFlowForPays" :key="item.appName" style="margin-bottom: 2px;">
                    <a-tag color="#2db7f5">{{ item.typeName | dealConvert }}</a-tag>
                    <span style="color:#729ED5;background:#e7f5f7">{{ item.totalAccountForDealType.toFixed(2) | currency }}</span><br>
                  </div>
                </div>
              </template>
            </a-table>
          </div>
        </div>
      </a-card>
    </div>
  </page-header-wrapper>
</template>
<script>
import { queryMerchantReportUrl } from '@/api/manage'
import moment from 'moment'

const tableColumns = [
  { key: 'appName', title: '商户系统', dataIndex: 'appName', ellipsis: true, width: 108 },
  { key: 'accountTime', dataIndex: 'accountTime', title: '账单日期', width: 100 },
  { key: 'currency', title: '货币形式', scopedSlots: { customRender: 'CurrencySlot' }, ellipsis: true, width: 100 },
  { key: 'unit', title: '单位', scopedSlots: { customRender: 'UnitSlot' }, width: 100 },
  {
    title: '账单合计',
    children: [
      {
        title: '大写',
        key: 'totalAccountForTenant1',
        width: 150,
        scopedSlots: { customRender: 'bamountSlot' }
      },
      {
        title: '小写',
        key: 'totalAccountForTenant2',
        width: 150,
        scopedSlots: { customRender: 'samountSlot' }
      }
    ]
  },
  { key: 'accountForDepartmentRqs', title: '交易类别', scopedSlots: { customRender: 'DetailSlot' }, width: 210 }
]

    export default {
    props: {
      initData: { type: Boolean, default: true }, // 初始化列表数据， 默认true
      pageSize: { type: Number, default: 20 }, // 默认每页条数
      scrollX: { type: Number, default: 500 }, // 表格显示滚动条的宽度
      tableRowCrossColor: { type: Boolean, default: false } // 是隔行换色
    },
    data () {
      return {
        showLoading: false,
        fileLoading: false,
        jeeDate: undefined, // 自定义日期选择框所用状态
        lastSevenDays: true, // 最近七天是否显示
        ranges: {
              '今天': [moment(moment().startOf('day').valueOf()), moment(moment().endOf('day').valueOf())],
              '昨天': [moment(moment().add(-1, 'days').startOf('day').valueOf()), moment(moment().add(-1, 'days').endOf('day').valueOf())],
              '近七天': [moment(moment().add(-6, 'days').startOf('day').valueOf()), moment(moment().endOf('day').valueOf())],
              '本周': [moment(moment().week(moment().week()).startOf('week').valueOf()), moment(moment().week(moment().week()).endOf('week').valueOf())],
              '上周': [moment(moment().week(moment().week() - 1).startOf('week').valueOf()), moment(moment().week(moment().week() - 1).endOf('week').valueOf())],
              '本月': [moment().startOf('month'), moment().endOf('month')],
              '上月': [moment().month(moment().month() - 1).startOf('month'), moment().month(moment().month() - 1).endOf('month')],
              '近一月': [moment().startOf('month'), moment().endOf('month')],
              '近二月': [moment().startOf('month').subtract(1, 'month'), moment().endOf('month')],
              '近三月': [moment().startOf('month').subtract(2, 'month'), moment().endOf('month')],
              '近六月': [moment().startOf('month').subtract(5, 'month'), moment().endOf('month')],
              '本季度': [moment().startOf('quarter'), moment().endOf('quarter')],
              '上季度': [moment().quarter(moment().quarter() - 1).startOf('quarter'), moment().quarter(moment().quarter() - 1).endOf('quarter')],
              '去年': [moment().year(moment().year() - 1).startOf('year'), moment().year(moment().year() - 1).endOf('year')] },
      tableColumns: tableColumns,
      searchData: {},
      configData: {},
      apiResData: { total: 0, records: [] }, // 接口返回数据
      iPage: { pageNumber: 1, pageSize: this.pageSize }, // 默认table 分页/排序请求后端格式
      pagination: { total: 0, current: 1, pageSize: this.pageSize, showSizeChanger: true, showTotal: total => `共${total}条` } // ATable 分页配置项
      }
    },
    mounted () {
      this.fetchData(true)
    },
    created () {
      this.searchData.requestType = 1
      this.searchData.reportType = 'other'
      this.searchData.timeStart = moment(moment().add(-6, 'days').startOf('day').valueOf()).format('YYYY-MM-DD HH:mm:ss') // dateString[0]开始时间
      this.searchData.timeEnd = moment(moment().endOf('day').valueOf()).format('YYYY-MM-DD HH:mm:ss') // dateString[1]结束时间
    },
    computed: {
      totalPrice () {
      var total = this.apiResData.records.total ? this.apiResData.records.total : 0
      return total
      },
      typeList () {
      return this.apiResData.records.typeList
      },
      columnsCustomSlots () { // 自定义列插槽  1. 过滤器仅获取到包含slot属性的元素， 2. 返回slot数组
          return this.tableColumns.filter(item => item.scopedSlots).map(item => item.scopedSlots)
      }
    },
    methods: {
      queryFunc () {
        this.fetchData(true)
      },
      onClose () {
        this.visible = false
      },
      handleTableChange (pagination, filters, sorter) { // 分页、排序、筛选变化时触发
      this.pagination = pagination
      this.iPage = {
        pageSize: pagination.pageSize, // 每页条数
        pageNumber: pagination.current, // 当前页码
        sortField: sorter.columnKey, // 排序字段
        sortOrder: sorter.order, // 排序顺序
        ...filters // 过滤数据
      }
      this.fetchData()
    },
      moment,
      onChange (date, dateString) {
      this.searchData.requestType = 1
      this.searchData.reportType = 'other'
      this.searchData.timeStart = dateString[0] // 开始时间
      this.searchData.timeEnd = dateString[1] // 结束时间
      this.jeeDate = dateString[0] + ' ~ ' + dateString[1]
      this.lastSevenDays = false
      },
      iconClick (dates) {
        this.searchData.timeStart = moment(moment().add(-6, 'days').startOf('day').valueOf()).format('YYYY-MM-DD HH:mm:ss')
        this.searchData.timeEnd = moment(moment().endOf('day').valueOf()).format('YYYY-MM-DD HH:mm:ss')
        this.queryFunc()
        this.jeeDate = '最近七天'
        this.lastSevenDays = true
      },
      disabledDate (current) { // 今日之后日期不可选
      return current && current > moment().endOf('day')
    },
    convertCurrency (money) {
      var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      var cnIntRadice = ['', '拾', '佰', '仟']
      var cnIntUnits = ['', '万', '亿', '兆']
      var cnDecUnits = ['角', '分', '毫', '厘']
      var cnInteger = '整'
      var cnIntLast = '元'
      var maxNum = 999999999999999.9999
      var integerNum
      var decimalNum
      var chineseStr = ''
      var parts
      if (money === '') {
        return ''
      }
      money = parseFloat(money)
      if (money >= maxNum) {
        return ''
      }
      if (money === 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger
        return chineseStr
      }
      money = money.toString()
      if (money.indexOf('.') === -1) {
        integerNum = money
        decimalNum = ''
      } else {
        parts = money.split('.')
        integerNum = parts[0]
        decimalNum = parts[1].substr(0, 4)
      }
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0
        var IntLen = integerNum.length
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1)
          var p = IntLen - i - 1
          var q = p / 4
          var m = p % 4
          if (n === '0') {
            zeroCount++
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0]
            }
            zeroCount = 0
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q]
          }
        }
        chineseStr += cnIntLast
      }
      if (decimalNum !== '') {
        var decLen = decimalNum.length
        for (i = 0; i < decLen; i++) {
          n = decimalNum.substr(i, 1)
          if (n !== '0') {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i]
          }
        }
      }
      if (chineseStr === '') {
        chineseStr += cnNums[0] + cnIntLast + cnInteger
      } else if (decimalNum === '') {
        chineseStr += cnInteger
      }
      return chineseStr
    },
    fetchData (isToFirst = false) {
      const that = this
      if (isToFirst) {
        this.iPage.pageNumber = 1
        this.pagination.current = 1
      }
      // 更新检索数据
      this.showLoading = true
      queryMerchantReportUrl(Object.assign({}, this.iPage, this.searchData), {}).then(resData => {
        this.pagination.total = resData.total // 更新总数量
        this.apiResData = resData // 列表数据更新
        this.showLoading = false // 关闭loading

        // 数据为0 ，并且为当前页面没有在第一页则需要自动跳转到上一页（解决，删除第二页数据全部删除后无数据的情况 ）
        if (resData.records.total === 0 && this.iPage.pageNumber > 1) {
          that.$nextTick(() => {
            // 最大页码
            const maxPageNumber = (resData.total / this.iPage.pageSize) + ((resData.total % this.iPage.pageSize) === 0 ? 0 : 1)
            if (maxPageNumber === 0) { // 已经无数据
              return false
            }
            // 跳转到的页码
            const toPageSize = (this.iPage.pageNumber - 1) > maxPageNumber ? maxPageNumber : (this.iPage.pageNumber - 1)
            this.iPage.pageNumber = toPageSize
            this.pagination.current = toPageSize
          })
          // return this.$infoBox.modalError(resData, '')
        }
      }).catch(res => {
        this.showLoading = false
        // this.$infoBox.modalError('错误', '')
      })
    },
    downLoad: function () {
        this.fileLoading = true
        this.searchData.requestType = 2
        queryMerchantReportUrl(this.searchData, { responseType: 'blob' }).then((res) => {
        if (res.code !== 0) {
          const link = document.createElement('a')
          const blob = new Blob([res], { type: 'application/octet-stream,charset=utf-8' })
          link.style.display = 'none'
          const url = URL.createObjectURL(blob)
          link.href = url
          link.setAttribute('download', '商户报表' + moment().format('YYYYMMDDHHmmss') + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        }
      this.$data.fileLoading = false
    })
    }
 }
}
</script>

<style lang="less">
.ant-card-body {
  padding: 24px;
  zoom: 1;
}
// 调整antdv 的table默认padding高度
.ant-descriptions-bordered .ant-descriptions-item-label {
  padding:10px 8px;
}
.ant-descriptions-bordered .ant.descriptions-item-content {
  padding:10px 8px;
}
.change-date-layout {
    padding-left: 11px;
    align-items: center;
    display:flex;
    justify-content:space-between;

    .change-date-icon {
      width:40px;
      height:36px;
      display:flex;
      align-items:center;
      justify-content:center;
    }
  }
</style>
